import java.util.Arrays;

public class HashBuck {

    @Override
    public String toString() {
        return "HashBuck{" +
                "array=" + Arrays.toString(array) +
                ", usedSize=" + usedSize +
                '}';
    }

    static class Node {
public int key;
public int val;
public Node next;

public Node(int key, int val) {
this.key = key;
this.val = val;
}
}

public Node[] array ;
public int usedSize;//记录 当前哈希桶当中 有效数据的个数
 public static final float DEFAULT_LOAD_FACTOR = 0.75F;

public HashBuck() {
this.array = new Node[10];
this.usedSize = 0;
}



    /**
* 存储key val
* @param key
* @param val
* @return
*/
public void put(int key,int val) {
    int ret = key%array.length;

    Node node = array[ret];
    while(null!=node) {
        if(key!=node.key) {
            node = node.next;
        }else {
            node.val = val;
            return;
        }
    }
    Node node1 = new Node(key,val);
    node1.next = array[ret];
    array[ret] = node1;
    usedSize++;

    if(loadFactor()>=DEFAULT_LOAD_FACTOR) {
        grow();
    }
}
    private float loadFactor() {
        return (usedSize*1.0f)/array.length;
    }
    private void grow() {

        Node[] newArray = new Node[2* array.length];
    //重新的哈希
    /**
     * 1. 遍历数组的每个元素的链表
     * 2. 每遍历到一个节点，就重新哈希  key % len
     * 3. 进行头插法
     */
     int len = newArray.length;
        for (int i = 0; i < array.length; i++) {
            if(null!=array[i]) {
                //原数组第一个结点
                Node src = array[i];
                //新数组的位置

                while(null!=src) {
                    int ret = (array[i].key)%len;
                    Node srcNext = src.next;
                    src.next = newArray[ret];
                    newArray[ret] = src;
                    src = srcNext;
                }
            }
        }
        this.array = newArray;
    }

/**
* 通过key值 获取val 值
* @param key
* @return
*/
public int get(int key) {
    int ret = key%array.length;

    Node node = array[ret];
    Node node1 = null;
    while(null!=node) {
        if(key!=node.key) {
            node = node.next;
        }else {
            return node.val;
        }
    }
    return -1;

}
}